import { Catch, HttpStatus, httpError } from '@midwayjs/core';
import { MidwayValidationError } from '@midwayjs/validate';
import { Context } from '@midwayjs/koa';

@Catch()
export class ErrorFilter {
  /**
   * 处理捕获到的错误，并返回相应的错误响应
   * @param err 捕获到的错误
   * @param ctx 请求上下文
   * @returns 返回错误响应对象
   */
  async catch(err: Error, ctx: Context) {
    let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;//500
    let message = 'Internal Server Error';
    if (err instanceof MidwayValidationError || err instanceof httpError.BadRequestError) {
      statusCode = HttpStatus.BAD_REQUEST;//400
      message = 'Bad request';
    } else if (err instanceof httpError.UnauthorizedError) {
      statusCode = HttpStatus.UNAUTHORIZED;//401
      message = 'Unauthorized';
    } else if (err instanceof httpError.ForbiddenError) {
      statusCode = HttpStatus.FORBIDDEN;//403
      message = 'Forbidden';
    } else if (err instanceof httpError.NotFoundError) {
      statusCode = HttpStatus.NOT_FOUND;//404
      message = 'Not Found';
    } else if (err instanceof httpError.ConflictError) {
      statusCode = HttpStatus.CONFLICT;//409
      message = 'Conflict';
    } 
    return {
      code: statusCode,
      // error: err.stack, // 开发模式下使用
      error: err.message, // 生产模式下使用
    };
  }
}